/********************************************************************
 * PROJECT: CSAIR ROST PROJECT.
 * SUPPLIER: FOREVER OPEN SOURCE SOFTWARE INC.
 ********************************************************************
 * FILE: ColorCache.java
 * (C) Copyright Foliage Team 2013, All Rights Reserved.
 ********************************************************************/
package org.foliage.rcp.ui.graphics;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

@SuppressWarnings({ "rawtypes", "unchecked" })
public final class ColorCache {

	public static final RGB BLACK = new RGB(0, 0, 0);
	public static final RGB WHITE = new RGB(255, 255, 255);

	private static Map cache;
	private static ColorCache instance;

	private ColorCache() {
		if (cache == null) {
			cache = new HashMap();
		}
	}
	
	private static void checkInstance() {
		if (instance == null) {
			instance = new ColorCache();
		}
	}

	private void dispose() {
		checkInstance();

		final Iterator iterator = cache.values().iterator();
		while (iterator.hasNext()) {
			((Color) iterator.next()).dispose();
		}

		cache.clear();
	}
	
	public static void disposeAll() {
		instance.dispose();
	}

	public static void disposeCachedColor() {
		final Iterator iterator = cache.values().iterator();
		while (iterator.hasNext()) {
			((Color) iterator.next()).dispose();
		}

		cache.clear();
	}

	public static Color getWhite() {
		checkInstance();
		return getColor(WHITE);
	}

	public static Color getBlack() {
		checkInstance();
		return getColor(BLACK);
	}

	public static Color getColor(final RGB rgb) {
		checkInstance();
		Color color = (Color) cache.get(rgb);

		if (color == null) {
			color = new Color(Display.getCurrent(), rgb);
			cache.put(rgb, color);
		}

		return color;
	}

	public static Color getColor(final int red, final int green, final int blue) {
		checkInstance();
		return getColor(new RGB(red, green, blue));
	}

}
